package com.ysy.persimmons.common.util;



import com.ysy.persimmons.common.constant.DateConstants;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;

/**
 *
 * @author yangSy git地址：git地址：url:<a href="https://gitee.com/ysyGit01/persimmons"/>
 * @date 2025/5/4
 */

public class DateUtils {

    /**
     * LocalDateTime 转时间戳
     *
     * @param localDateTime LocalDateTime
     * @return 转化后的时间戳
     */
    public static long localDateTimeTimestamp(LocalDateTime localDateTime) {
        return localDateTime.toInstant(ZoneOffset.UTC).toEpochMilli();
    }

    /**
     * LocalDateTime 转 String 字符串
     * @param time
     * @return
     */
    public static String localDateTimeString(LocalDateTime time) {
        return time.format(DateConstants.DATE_FORMAT_Y_M_D_H_M_S);
    }

    public static String formatRelativeTime(LocalDateTime dateTime){
        // 当前时间
        LocalDateTime now = LocalDateTime.now();

        // 计算与当前时间的差距
        long daysDiff = ChronoUnit.DAYS.between(dateTime, now);
        long hoursDiff = ChronoUnit.HOURS.between(dateTime, now);
        long minutesDiff = ChronoUnit.MINUTES.between(dateTime, now);
        // 如果是今天
        if(daysDiff < 1) {
            // 如果是几分钟前
            if (hoursDiff < 1) {
                return minutesDiff + "分钟前";
            }
            // 如果是几个小时前
            else {
                return hoursDiff + "小时前";
            }
            // 如果是昨天
        } else if (daysDiff == 1){
            return "昨天" + dateTime.format(DateConstants.DATE_FORMAT_H_M);
            // 如果是几前天
        } else if(daysDiff < 7) {
            return daysDiff + "天前";
            // 如果今年
        } else if (dateTime.getYear() == now.getYear()) {
            return dateTime.format(DateConstants.DATE_FORMAT_M_D);
            // 如果去年或更早
        } else {
            return dateTime.format(DateConstants.DATE_FORMAT_Y_M_D);
        }
    }
}
